package com.health.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.health.config.AlipayConfig;
import com.health.vo.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    /**
     * 获取支付表单
     */
    @PostMapping("/getPayForm")
    public Result addOrder(String orderNo, Double totalAmount, String subject, String body) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //表单
        String form = alipayClient.pageExecute(alipayRequest).getBody();
        return new Result(true, "获取支付宝表单页面成功", form);
    }

    /**
     * 获取支付状态
     */
    @GetMapping("/getPayStatus")
    public Result getPayStatus(String orderNo) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNo + "\"," +
                "\"trade_no\":\"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //解析json数据
        JSONObject response = JSONObject.parseObject(result).getJSONObject("alipay_trade_query_response");
        //获取状态码
        String code = response.getString("code");
        if (!StringUtils.isEmpty(code) && code.equals("10000")) {
            return new Result(true, "支付成功");
        }

        return new Result(false, response.getString("sub_msg"));
    }
}
